<?php
//核心业务操作
global $_W, $_GPC;
load()->func('tpl');
$html_title = $_W['current_module']['title'];
$op = !empty($_GPC['op']) ? $_GPC['op'] : '';
$extra = !empty($_GPC['extra']) ? $_GPC['extra'] : '';
$isactive = 'core';//底部菜单切换效果

//发圈操作
if ($op == 'faquan') {
    $html_title = '开始分享到朋友圈';
    checkMobileLogin(true);
    $user_id = session('user_id');
    $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
    $setting = cmf_get_option('share_setting');
    $setting['thumb1'] = cmf_get_upload_url($setting['thumb1']);
    $setting['detail'] = explode("\n", trim($setting['detail']));
    $shareCon = array(
        'title' => $setting['share_title'],
        'imgUrl' => $setting['thumb1'],
        'desc' => $setting['share_content']
    );
    $jssdk = $_W['account']['jssdkconfig'];
    include $this->template('core_faquan');
    exit;
}
//发圈上传截图
if ($op == 'faquan_submit') {

    if (is_post() && $extra == 'upload') {
        $file = $_FILES["uploader_pic1"];
        if (!$file) {
            ajaxError('请上传图片');
        }
        $allowedExts = array("jpeg", "jpg", "png");
        $temp = explode("/", $file["type"]);
        $extension = end($temp);

        if (!in_array($extension, $allowedExts)) {
            ajaxError('只能上传图片文件');
        }
        if ($file["size"] > 4 * 1024 * 1024) {
            ajaxError('图片大小超过4M');
        }
        $file_dir = '../attachment/common/image/' . date('Ymd');//web文件夹的上层即为根目录
        if (!file_exists($file_dir)) {
            mkdirs($file_dir);
        }
        $filename = $file_dir . '/' . md5(time() . uniqid()) . '.' . $extension;
        $res = move_uploaded_file($file["tmp_name"], $filename);
        if (!$res) {
            @unlink($filename);
            ajaxError('上传失败，稍后重试');
        }
        $imgurl = substr($filename, 14);
        if ($file['size'] > 2 * 1024 * 1024) {
            $new_path = $file_dir . '/' . md5(time() . uniqid()) . '.' . $extension;
            $res = image_png_size_add($filename, $new_path);
            if (!$res) {
                @unlink($filename);
                ajaxError('上传失败');
            }
            $imgurl = substr($new_path, 14);
        }
        $pic1 = cmf_get_upload_url($imgurl);

        $file = $_FILES["uploader_pic2"];
        if (!$file) {
            ajaxError('请上传图片');
        }
        $temp = explode("/", $file["type"]);
        $extension = end($temp);

        if (!in_array($extension, $allowedExts)) {
            ajaxError('只能上传图片文件');
        }
        if ($file["size"] > 4 * 1024 * 1024) {
            ajaxError('图片大小超过4M');
        }
        $filename = $file_dir . '/' . md5(time() . uniqid()) . '.' . $extension;
        $res = move_uploaded_file($file["tmp_name"], $filename);
        if (!$res) {
            @unlink($filename);
            ajaxError('上传失败，稍后重试');
        }
        $imgurl = substr($filename, 14);
        if ($file['size'] > 2 * 1024 * 1024) {
            $new_path = $file_dir . '/' . md5(time() . uniqid()) . '.' . $extension;
            $res = image_png_size_add($filename, $new_path);
            if (!$res) {
                @unlink($filename);
                ajaxError('上传失败');
            }
            $imgurl = substr($new_path, 14);
        }
        $pic2 = cmf_get_upload_url($imgurl);
        ajaxSuccess('上传成功', [$pic1, $pic2]);

    } else if (is_post() && $extra == '') {
        $picarr = input('picarr');
        if (empty($picarr) || false === stripos($picarr, ';')) {
            ajaxError('请上传两张发圈截图');
        }
        $picarr = explode(';', trim($picarr, ';'));
        $user_id = session('user_id');
        if (!$user_id) {
            foreach ($picarr as $v) {
                @unlink(cmf_get_upload_url($v));
            }
            ajaxError('您尚未登录');
        }
        $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
        if ($user['user_level'] < 1) {
            foreach ($picarr as $v) {
                @unlink(cmf_get_upload_url($v));
            }
            ajaxError('只有VIP会员可以进行发圈任务');
        }

        $startTime = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endTime = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        $taskCount = pdo_fetchcolumn("select count(*) number from " . tablename('yq_haircircle_share_task_log') . " where user_id=$user_id and (create_time between $startTime and $endTime) and review_status!=0");
        if ($taskCount >= 2) {
            foreach ($picarr as $v) {
                @unlink(cmf_get_upload_url($v));
            }
            ajaxError('发圈任务每天只能进行两次');
        }
        $log['user_id'] = $user_id;
        $log['submit_img'] = implode(';', $picarr);
        $log['create_time'] = time();
        $log['review_status'] = 0;
        $res = pdo_insert('yq_haircircle_share_task_log', $log);
        if (empty($res)) {
            foreach ($picarr as $v) {
                @unlink(cmf_get_upload_url($v));
            }
            ajaxError('上传失败，请稍后重试');
        }
        ajaxSuccess('上传成功,请耐心等待审核');
    }
    $html_title = '发圈上传截图';
    checkMobileLogin(true);
    $user_id = session('user_id');
    $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
    $setting = cmf_get_option('share_setting');
    $setting['thumb1'] = cmf_get_upload_url($setting['thumb1']);
    $setting['detail'] = explode("\n", trim($setting['detail']));
    $jssdk = $_W['account']['jssdkconfig'];
    include $this->template('core_faquan_submit');
    exit;
}
//提现操作
if ($op == 'cashout') {
    if (is_post()) {
        $user_id = session('user_id');
        if (!$user_id) {
            ajaxReturn('您尚未登录');
        }
        $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
        if (empty($user['truename']) || empty($user['idno'])) {
            ajaxError('请先在个人中心完善个人信息');
        }
        $alipay_name = input('alipay_name');
        $alipay_account = input('alipay_account');
        if (empty($alipay_name) || empty($alipay_account)) {
            ajaxError('请填写正确的提现信息');
        }

        //用户提现的金额
        $money = floatval(input('money'));
        if ($money <= 0) {
            ajaxError('提现金额错误');
        }

        $task_param_setting = cmf_get_option('task_param_setting');
        $tx_min = $task_param_setting['tx_min'];
        if ($money < $task_param_setting['tx_min']) {
            ajaxError('提现最小金额为' . $tx_min . '元');
        }

        //用户提现所需手续费
        $proce = $task_param_setting['tx_fee'];

        $user_money = $user['user_money'];
        if ($user_money < $money * (1 + $proce / 100)) {
            $this->error('余额不足');
        }

        $proce = number_format($money * $proce / 100, 2);//百分比计算

        //写入支付宝信息
        pdo_update('yq_haircircle_users', array('alipay_name' => $alipay_name, 'alipay_account' => $alipay_account), array('id' => $user_id));

        pdo_begin();

        //写入提现日志
        $add['user_id'] = $user_id;
        $add['cash_money'] = $money;
        $add['tx_fee'] = $proce;
        $add['tx_mark'] = '';
        $add['create_time'] = time();
        $res = pdo_insert('yq_haircircle_cashout', $add);
        if (empty($res)) {
            pdo_rollback();
            ajaxError('提现失败(写入提现日志出现异常),请稍后重试');
        }

        //用户金额变动记录
        $log['oid'] = pdo_insertid();
        $log['user_id'] = $user_id;
        $log['type'] = -1;
        $log['change'] = 0 - $money - $proce;
        $log['balance'] = $user_money - $money - $proce;
        $log['mobile'] = $user['mobile'];
        $log['remark'] = '发起提现';
        $log['create_time'] = time();
        $res = pdo_insert('yq_haircircle_user_money_log', $log);
        if (empty($res)) {
            pdo_rollback();
            ajaxError('提现失败(写入用户余额变更日志出现异常),请稍后重试');
        }

        //用户表中减少金额
        $res = pdo_update('yq_haircircle_users', array('user_money' => $user_money - $money - $proce), array('id' => $user_id));
        if (empty($res)) {
            pdo_rollback();
            ajaxError('提现失败(扣除账户余额出现异常),请稍后重试');
        }

        pdo_commit();

        ajaxSuccess('提现成功,我们的管理员会马上帮您审核,请稍稍等待');
    }

    $html_title = '我要提现';
    checkMobileLogin(true);
    $user_id = session('user_id');
    $user = pdo_get('yq_haircircle_users', array('id' => $user_id), array('user_money'));
    $task_param_setting = cmf_get_option('task_param_setting');
    include $this->template('core_cashout');
    exit;
}
//任务提交操作
if ($op == 'task_submit') {
    if (is_post() && $extra == 'upload') {
        $img = input('img');
        // 获取图片
        if (empty($img)) {
            ajaxError('请选择图片');
        }
        try {
            list($type, $data) = explode(',', $img);
            // 判断类型
            if (strstr($type, 'image/jpeg') != '') {
                $ext = '.jpg';
            } elseif (strstr($type, 'image/gif') != '') {
                $ext = '.gif';
            } elseif (strstr($type, 'image/png') != '') {
                $ext = '.png';
            }
            $uploadPath = '../attachment/common/image/' . date('Ymd');//web文件夹的上层即为根目录
            if (!file_exists($uploadPath)) {
                @mkdirs($uploadPath);
            }
            $new_file = $uploadPath . DS . md5(uniqid() . time()) . $ext;
            if (file_put_contents($new_file, base64_decode($data))) {
                if (!file_exists($new_file)) {
                    ajaxError('上传失败，请稍后重试');
                }
                if (filesize($new_file) > 2 * 1024 * 1024) {
                    $new_path = $uploadPath . '/' . md5('thumb_'  . uniqid() . time()) . '.' . $extension;
                    $res = image_png_size_add($new_file, $new_path);
                    if (!$res) {
                        @unlink($new_file);
                        ajaxError('上传失败，请稍后重试');
                    }
                    ajaxSuccess('上传成功', cmf_asset_relative_url($new_path));
                }
                ajaxSuccess('上传成功', cmf_asset_relative_url($new_file));
            } else {
                ajaxError('上传失败，请稍后重试');
            }
        } catch (\Exception $e) {
            ajaxError('上传失败：' . $e->getMessage());
        }
    }
    if (is_post() && $extra == '') {
        $picarr = !empty($_GPC['picarr']) ? input('picarr') : '';
        if (!empty($picarr)) {
            $picarr = implode($picarr, ';');
        }
        $user_id = session('user_id');
        if (!$user_id) {
            if(!empty($picarr) && $picarr = explode(';',$picarr)){
                foreach ($picarr as $v) {
                    @unlink(cmf_get_upload_url($v));
                }
                ajaxError('您尚未登录');
            }
        }
        $user = pdo_get('yq_haircircle_users', array('id' => $user_id));

        $taskid = input('taskid');
        $task = pdo_get('yq_haircircle_task', array('id' => $taskid, 'delete_time' => 0));
        if (empty($task)) {
            ajaxError('任务不存在或已被删除，不能再提交');
        }

        if ($task['end_time'] < time()) {
            //更改接取状态
            pdo_update('yq_haircircle_task_receive', array('receive_status' => 1), array('taskid' => $taskid));
            ajaxError('任务已过期，不能再提交，请期待下一期');
        }

        $receive = pdo_get('yq_haircircle_task_receive', array('taskid' => $taskid, 'user_id' => $user_id));
        if (empty($receive)) {
            ajaxError('您还没有接取该任务');
        }

        if ($receive['receive_status'] > 1) {
            ajaxError('您已经提交过了');
        }

        pdo_begin();
        //改字段
        $data['receive_status'] = 2;
        $data['submit_time'] = time();
        $data['submit'] = isset($_GPC['submit']) ? input('submit') : '';
        $data['submit_img'] = $picarr;
        $res = pdo_update('yq_haircircle_task_receive', $data, array('id' => $receive['id']));
        if (empty($res)) {
            pdo_rollback();
            ajaxError('任务提交失败，请稍后重试');
        }
        //写用户任务日志
        $log['taskid'] = $taskid;
        $log['receive_id'] = $receive['id'];
        $log['user_id'] = $user_id;
        $log['mobile'] = $user['mobile'];
        $log['task_money'] = $task['task_money'];
        $log['task_title'] = $task['task_title'];
        $log['remark'] = "提交任务";
        $log['create_time'] = time();
        $log['type'] = 2;//用户提交任务
        $res = pdo_insert('yq_haircircle_user_task_log', $log);
        if (empty($res)) {
            pdo_rollback();
            ajaxError('任务提交失败，请稍后重试');
        }
        pdo_commit();
        ajaxSuccess('任务提交成功，请等待管理员审核');
    }
    $taskid = input('taskid');
    $html_title = '任务提交';
    $task = pdo_get('yq_haircircle_task',array('id' => $taskid));
    checkMobileLogin(true);
    include $this->template('core_task_submit');
    exit;
}


//升级操作
if ($op == 'upgrade') {
    $html_title = '升级VIP';
    checkMobileLogin(true);
    $user_id = session('user_id');
    $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
    $fenxiao_setting_v1 = cmf_get_option('fenxiao_setting_v1.0');
    $share_setting = cmf_get_option('share_setting');
    $openId = '';
    if ($user['user_level'] < 1) {
        $pay_setting = cmf_get_option('pay_setting');
        $jsweixinpay = isset($pay_setting['jsweixinpay']) ? $pay_setting['jsweixinpay'] : false;
        if (!$jsweixinpay) {
            message('暂未配置支付信息',$this->createMobileUrl('member', array('op' => 'index')));
        }
        //①、获取用户openid
        $file = IA_ROOT . '/addons/' . ModuleName() . '/api/JSWeixinpayAPI/JSWeixinpayAPI.api.php';
        if (is_file($file)) {
            require_once $file;
        } else {
            return false;
        }
        $wxPay = new JSWeixinpayAPI($jsweixinpay['mchid'], $jsweixinpay['appid'], $jsweixinpay['appkey'], $jsweixinpay['apikey']);
        $openId = $wxPay->GetOpenid();      //获取openid
        if (!$openId) {
            message('获取openid失败',$this->createMobileUrl('member', array('op' => 'index')));
        }
    }
    include $this->template('core_upgrade');
    exit;
}
//传openid、fee
if ($op == 'upgarde_weixinjspay_ordermake') {
    $user_id = session('user_id');
    if (!$user_id) {
        ajaxError('您还未登录');
    }
    $openId = input('openId');
    if (empty($openId)) {
        ajaxError('未获取到会员openId,请重新进入此页');
    }
    $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
    $fee = input('fee');
    if ($fee <= 0) {
        ajaxError('支付参数不合法');
    }
    $fenxiao_setting_v1 = cmf_get_option('fenxiao_setting_v1.0');

    if ($fenxiao_setting_v1['vip_upgrade_price'] != $fee) {
        ajaxError('支付参数不合法');
    }

    $chargerecord['order_sn'] = cmf_get_order_sn();
    $chargerecord['user_id'] = $user_id;
    $chargerecord['payprice'] = $fee;
    $chargerecord['paytype'] = 1;//微信支付
    $chargerecord['upgrade_type'] = 1;
    $chargerecord['is_true'] = 0;
    $chargerecord['fx_state'] = 0;
    $chargerecord['create_time'] = time();

    $res = pdo_insert('yq_haircircle_upgrade_order', $chargerecord);
    if (empty($res)) {
        ajaxError('订单生成失败，请稍后重试');
    }

    $pay_setting = cmf_get_option('pay_setting');
    $jsweixinpay = $pay_setting['jsweixinpay'];
    $file = IA_ROOT . '/addons/' . ModuleName() . '/api/JSWeixinpayAPI/JSWeixinpayAPI.api.php';
    if (is_file($file)) {
        require_once $file;
    } else {
        return false;
    }
    $wxPay = new JSWeixinpayAPI($jsweixinpay['mchid'], $jsweixinpay['appid'], $jsweixinpay['appkey'], $jsweixinpay['apikey']);
    //②、统一下单
    $outTradeNo = $chargerecord['order_sn'];
    $payAmount = 0.01;
//    $payAmount = $fee;
    $orderName = '升级VIP会员';    //订单标题
    $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/addons/yq_haircircle/notify.php';
    $payTime = time();      //付款时间
    $jsApiParameters = $wxPay->createJsBizPackage($openId, $payAmount, $outTradeNo, $orderName, $notifyUrl, $payTime);
    ajaxSuccess('下单成功，进入支付...', $jsApiParameters);
}

//完善信息操作
if ($op == 'wanshan') {
    if (is_post()) {
        $user_id = session('user_id');
        if (!$user_id) {
            ajaxError('您还未登录');
        }
        $user = pdo_get('yq_haircircle_users', array('id' => $user_id));

        $truename = input('truename');
        if (!checkTruename($truename)) {
            ajaxError('姓名格式错误');
        }
        $idno = input('idno');
        if (!isCreditNo($idno)) {
            ajaxError('身份证号码错误');
        }
        $alipay_account = input('alipay_account');
        if (empty($alipay_account)) {
            ajaxError('请输入支付宝账号');
        }
        $alipay_name = input('alipay_name');
        if (!checkTruename($alipay_name)) {
            ajaxError('请输入正确的支付宝姓名');
        }
        $bank_card = input('bank_card');
        if (!checkIdno($bank_card)) {
            ajaxError('请输入正确的银行卡');
        }
        $bank_truename = input('bank_truename');
        if (!checkTruename($bank_truename)) {
            ajaxError('请输入正确的银行卡姓名');
        }
        $bank_branch = input('bank_branch');
        if (!checkTruename($bank_branch)) {
            ajaxError('请输入正确的开户行');
        }

        $url = 'http://' . $_SERVER['HTTP_HOST'] . '/app/' . $this->createMobileUrl('public', array('op' => 'register', 'pid' => $user_id));
        $tuiguang_setting = cmf_get_option('tuiguang_setting');
        if(isset($tuiguang_setting['thumb1']) && !empty($tuiguang_setting['thumb1'])){
            $bg = '../attachment/' . cmf_asset_relative_url($tuiguang_setting['thumb1']);
        }else{
            $bg = '../addons/yq_haircircle/qrcode-background.png';
        }
        $qrcode = cmf_get_qrcode($url,251,$bg);
        if (!$qrcode) {
            ajaxError('保存信息失败，更新二维码失败');
        }
        if (!empty($user['qrcode'])) {
            @unlink('../attachment/' . $user['qrcode']);
        }
        $userInfo = [
            'truename' => $truename,
            'alipay_account' => $alipay_account,
            'alipay_name' => $alipay_name,
            'bank_card' => $bank_card,
            'bank_name' => $bank_name,
            'bank_branch' => $bank_branch,
            'idno' => $idno,
            'bank_truename' => $bank_truename,
            'qrcode' => $qrcode
        ];
        $res = pdo_update('yq_haircircle_users', $userInfo, array('id' => $user_id));
        if (!empty($res)) {
            ajaxSuccess('保存信息成功');
        }
        $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
        session('user', $user);
        ajaxError('更新信息失败，请稍后重试');
    }
    $html_title = '完善信息';
    checkMobileLogin(true);
    $user_id = session('user_id');
    $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
    include $this->template('core_wanshan');
    exit;
}
//分享任务
if ($op == 'fenxiang') {
    $html_title = '我的分享';
    checkMobileLogin(true);
    $user_id = session('user_id');
    $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
    $url = 'http://' . $_SERVER['HTTP_HOST'] . '/app/' . $this->createMobileUrl('public', array('op' => 'register', 'pid' => $user_id));
    $tuiguang_setting = cmf_get_option('tuiguang_setting');
    if(isset($tuiguang_setting['thumb1']) && !empty($tuiguang_setting['thumb1'])){
        $bg = '../attachment/' . cmf_asset_relative_url($tuiguang_setting['thumb1']);
    }else{
        $bg = '../addons/yq_haircircle/qrcode-background.png';
    }

    $qrcode = cmf_get_qrcode($url,251,$bg);

    if (!$qrcode) {
        message('获取二维码失败');
    }

    $user['qrcode'] = $qrcode;
    include $this->template('core_fenxiang');
    exit;
}
//抢任务
if ($op == 'rob') {
    $id = intval($_GPC['id']);
    if (!session('user_id')) {
        ajaxReturn(['code' => USER_NOT_LOGIN, 'msg' => '您尚未登录']);
    }
    $user_id = session('user_id');
    $user = pdo_get('yq_haircircle_users', array('id' => $user_id));
    if (empty($user)) {
        ajaxError('非法用户');
    }
    if ($user['user_status'] != 1) {
        ajaxError('您已被管理员禁用');
    }
    if ($user['user_level'] < 1) {
        ajaxError('您还不是会员,请到个人中心升级用户');
    }
    $receive = pdo_get('yq_haircircle_task_receive', array('taskid' => $id, 'user_id' => $user_id));
    if (!empty($receive)) {
        ajaxError('您已经接过此任务啦');
    }
    $task = pdo_get('yq_haircircle_task', array('id' => $id));
    if (empty($task)) {
        ajaxError('该任务不存在');
    }

    if ($task['delete_time'] > 0) {
        ajaxError('该任务已删除');
    }

    if ($task['end_time'] < time()) {
        pdo_update('yq_haircircle_task_receive', array('receive_status' => 1), array('taskid' => $id, 'receive_status' => 0));
        ajaxError('该任务已过期');
    }

    if ($task['release_num'] < 1) {
        ajaxError('该任务已经被抢完了，请关注其他任务');
    }

    //单日接取上限
    $task_param_setting = cmf_get_option('task_param_setting');
    if ($max = $task_param_setting['task_receive_max']) {
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        $where = "user_id=$user_id and (receive_time between $beginToday and $endToday)";
        $total = pdo_fetchcolumn('SELECT COUNT(*) AS `number` FROM ' . tablename('yq_haircircle_task_receive') . ' WHERE ' . $where);
        if ($total >= $max) {
            ajaxError('每天最多接' . $max . '个哦，请明天再来吧');
        }
    }

    pdo_begin();

    //插入任务订单
    $data['user_id'] = $user_id;
    $data['taskid'] = $id;
    $data['receive_time'] = time();
    $data['receive_status'] = 0;
    $res = pdo_insert('yq_haircircle_task_receive', $data);
    if (empty($res)) {
        pdo_rollback();
        ajaxError('抢任务失败,请稍后重试');
    }
    //写用户任务日志
    $log['taskid'] = $id;
    $log['receive_id'] = pdo_insertid();
    $log['user_id'] = $user_id;
    $log['mobile'] = $user['mobile'];
    $log['task_money'] = $task['task_money'];
    $log['task_title'] = $task['task_title'];
    $log['remark'] = "抢任务";
    $log['create_time'] = time();
    $log['type'] = 1;//接受任务
    $res = pdo_insert('yq_haircircle_user_task_log', $log);
    if (empty($res)) {
        pdo_rollback();
        ajaxError('抢任务失败,请稍后重试');
    }

    pdo_commit();

    ajaxSuccess('您已经抢成功啦，快去完成任务吧');
}